<?php

namespace App\Models;

use App\Helpers\QiniuHelper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\Models\WechatUpload
 *
 * @property int $id
 * @property string $key 文件名的key
 * @property string $title 文件标题
 * @property float $duration 媒体时长(秒)
 * @property float $price 售价
 * @property string $openid openid
 * @property int $status 0-正常，1-隐藏，2-命名中
 * @property int $type 1-图片，2-视频
 * @property int $buy_count 购买次数
 * @property int $up 点赞次数
 * @property int $down 踩坑次数
 * @property float $total_price 购买总额
 * @property int $qiniu_ready 0-处理中，1-就绪
 * @property \Carbon\Carbon|null $created_at
 * @property \Carbon\Carbon|null $updated_at
 * @property string|null $deleted_at
 * @property-read mixed $guest_image
 * @property-read mixed $type_word
 * @property-read mixed $url
 * @property-read \App\Models\Member $member
 * @method static bool|null forceDelete()
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WechatUpload onlyTrashed()
 * @method static bool|null restore()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereBuyCount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereDeletedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereDown($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereDuration($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereKey($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereOpenid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload wherePrice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereQiniuReady($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereTitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereTotalPrice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereUp($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\WechatUpload whereUpdatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WechatUpload withTrashed()
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WechatUpload withoutTrashed()
 * @mixin \Eloquent
 */
class WechatUpload extends Model
{
    use SoftDeletes;

    protected $fillable = ['title', 'min_price', 'max_price', 'status', 'promote_url'];

    const TYPES = [
        1 => '图片',
        2 => '视频',
    ];

    const STATUSES = [
        0 => '正常',
        1 => '隐藏',
        2 => '设置标题价格',
    ];


    public function getTypeWordAttribute()
    {
        if (array_key_exists($this->type, self::TYPES)) {
            return self::TYPES[$this->type];
        }
        return '未知';
    }

    public function getStatusWordAttribute()
    {
        if (array_key_exists($this->status, self::STATUSES)) {
            return self::STATUSES[$this->status];
        }
        return '未知';
    }

    public function getGuestImageAttribute()
    {
        $url = 'http://' . env('QINIU_DOMAIN') . '/' . $this->key;
        switch ((int) $this->type) {
            case 1:
                $url .= '_blur.jpg';
                break;
            case 2:
                $url .= '_thumb.jpg';
                break;
        }
        return $url;
    }

    public function member()
    {
        return $this->hasOne(Member::class, 'openid', 'openid');
    }

    public function getUrlAttribute()
    {
        $url = 'http://' . env('QINIU_DOMAIN') . '/' . $this->key;
        switch ((int) $this->type) {
            case 1:
                $url .= '.jpg';
                break;
            case 2:
                $url .= '.mp4';
                break;
        }
        return $url;
    }

    public function my_wechat_uploads()
    {
        return $this->hasMany(MyWechatUpload::class);
    }

    public function hasOwn($openid)
    {
        if ($this->openid == $openid) {
            return true;
        }
        if (!count($this->my_wechat_uploads)) {
            return false;
        }
        $uploads = $this->my_wechat_uploads;
        if (!count($uploads)) {
            return false;
        }
        foreach ($uploads as $upload) {
            if ($upload->openid == $openid) {
                return true;
            }
        }
        return false;
    }

    public function getPromotionUrlAttribute()
    {
        if (!strlen($this->attributes['promote_url'])) {
            $domain = Domain::one();
            $url = "http://{$domain}/wechat/view?id={$this->id}";
            $shortUrl = wechat_short_url($url);
            if (!strlen($shortUrl)) {
                $shortUrl = $url;
            }
            $this->attributes['promote_url'] = $shortUrl;
            $this->save();
        }
        return $this->attributes['promote_url'];
    }

    public function getMinPriceAttribute()
    {
        $min = isset($this->attributes['min_price']) ? $this->attributes['min_price'] : 0;
        if ($min < 0.01) {
            $min = 0.01;
        }
        return $min;
    }

    public function getMaxPriceAttribute()
    {
        $min = $this->min;
        $max = isset($this->attributes['max_price']) ? $this->attributes['max_price'] : 0;
        if ($max < $min) {
            $max = $min;
        }
        return $max;
    }

    public function getDurationWordAttribute()
    {
        if (2 == $this->type) {
            return format_time($this->duration);
        }
        return '-';
    }

    public function getByteAttribute()
    {
        if ((bool) $this->attributes['byte']) {
            return $this->attributes['byte'];
        }
        $fileName = $this->key;
        switch ($this->type) {
            case 1:
                $fileName .= '.jpg';
                break;
            case 2:
                $fileName .= '.mp4';
                break;
        }
        $fileInfo = QiniuHelper::fileInfo($fileName);
        if (is_array($fileInfo) && isset($fileInfo['fsize'])) {
            $this->attributes['byte'] = $fileInfo['fsize'];
            $this->save();
        }
        return $this->attributes['byte'];
    }
}
